package org.jeecg.modules.solitaire_app.app.controller;

import java.math.BigDecimal;
import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.solitaire_app.app.entity.YsySystem;
import org.jeecg.modules.solitaire_app.app.entity.YsyUsers;
import org.jeecg.modules.solitaire_app.app.entity.YsyWalletLog;
import org.jeecg.modules.solitaire_app.app.entity.YsyWithdrawLog;
import org.jeecg.modules.solitaire_app.app.mapper.YsyUsersMapper;
import org.jeecg.modules.solitaire_app.app.mapper.YsyWalletLogMapper;
import org.jeecg.modules.solitaire_app.app.query.WithdrawLogQuery;
import org.jeecg.modules.solitaire_app.app.service.IYsySystemService;
import org.jeecg.modules.solitaire_app.app.service.IYsyWalletLogService;
import org.jeecg.modules.solitaire_app.app.service.IYsyWithdrawLogService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.system.entity.SysAnnouncement;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysAnnouncementService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 提现记录表
 * @Author: jeecg-boot
 * @Date: 2023-09-07
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "提现记录表")
@RestController
@RequestMapping("/app/ysyWithdrawLog")
public class YsyWithdrawLogController extends JeecgController<YsyWithdrawLog, IYsyWithdrawLogService> {
    @Autowired
    private IYsyWithdrawLogService ysyWithdrawLogService;
    @Autowired
    private YsyUsersMapper ysyUsersMapper;
    @Autowired
    private IYsyWalletLogService walletLogService;
    @Autowired
    private IYsySystemService ysySystemService;
    @Autowired
    private YsyWalletLogMapper ysyWalletLogMapper;
    @Autowired
    private ISysAnnouncementService sysAnnouncementService;

    /**
     * 分页列表查询
     *
     * @param ysyWithdrawLog
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "提现记录表-分页列表查询")
    @ApiOperation(value = "提现记录表-分页列表查询", notes = "提现记录表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(YsyWithdrawLog ysyWithdrawLog,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<YsyWithdrawLog> queryWrapper = QueryGenerator.initQueryWrapper(ysyWithdrawLog, req.getParameterMap());
        Page<YsyWithdrawLog> page = new Page<YsyWithdrawLog>(pageNo, pageSize);
        IPage<YsyWithdrawLog> pageList = ysyWithdrawLogService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param withdrawLogQuery
     * @return
     */
    @AutoLog(value = "提现记录表-添加")
    @ApiOperation(value = "提现记录表-添加", notes = "提现记录表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody WithdrawLogQuery withdrawLogQuery) {
        YsyUsers ysyUsers = ysyUsersMapper.selectOne(Wrappers.<YsyUsers>lambdaQuery()
                .eq(YsyUsers::getId, withdrawLogQuery.getUserId()));

        if (ysyUsers.getBalance().compareTo(BigDecimal.ZERO) == 0) {
            return Result.error("可提现余额不足!!!");
        }

        if (withdrawLogQuery.getMoney().compareTo(BigDecimal.ZERO) == 0) {
            return Result.error("可提现余额不足!!!");
        }

        if (ysyUsers.getBalance().compareTo(withdrawLogQuery.getMoney()) == -1) {
            return Result.error("可提现余额不足!!!");
        }

        YsySystem ysySystem = ysySystemService.getOne(Wrappers.<YsySystem>lambdaQuery()
                .eq(YsySystem::getAppid, withdrawLogQuery.getAppId()));

        int commsition = 0;
        if (ObjectUtil.isEmpty(ysySystem)) {
            commsition = 1;
        } else {
            if (ObjectUtil.isEmpty(ysySystem.getCommission())) {
                commsition = 1;
            } else {
                commsition = ysySystem.getCommission();
            }
        }

        //判断用户是否绑定过银行卡
        if (ObjectUtil.isNull(ysyUsers.getYhkKhh()) && ObjectUtil.isNull(ysyUsers.getYhkNum())) {
            //绑定银行卡
            ysyUsers.setYhkKhh(withdrawLogQuery.getYhkKhh());
            ysyUsers.setYhkUserName(withdrawLogQuery.getYhkUserName());
            ysyUsers.setYhkNum(withdrawLogQuery.getYhkNum());
            ysyUsers.setYhkPhone(withdrawLogQuery.getYhkPhone());
            ysyUsersMapper.updateById(ysyUsers);
        }

        YsyWithdrawLog ysyWithdrawLog = new YsyWithdrawLog();
        BeanUtil.copyProperties(withdrawLogQuery, ysyWithdrawLog);
        ysyWithdrawLog.setUserPhone(ysyUsers.getPhone());
        ysyWithdrawLog.setUserName(ObjectUtil.isNull(ysyUsers.getRealName())
                ? ysyUsers.getNickName()
                : ysyUsers.getRealName());
        ysyWithdrawLog.setCommission(ysyWithdrawLog.getMoney().multiply(BigDecimal.valueOf(commsition / 100)));
        ysyWithdrawLog.setActualPrice(ysyWithdrawLog.getMoney().subtract(ysyWithdrawLog.getCommission()));

        ysyWithdrawLogService.save(ysyWithdrawLog);
        //扣除金额
        ysyUsers.setBalance(ysyUsers.getBalance().subtract(ysyWithdrawLog.getMoney()));
        ysyUsersMapper.updateById(ysyUsers);


        //发公告通知处理
        SysAnnouncement sysAnnouncement = new SysAnnouncement();
        sysAnnouncement.setTitile("提现通知");
        sysAnnouncement.setMsgContent("有用户申请了提现，请尽快去处理！！！！");
        sysAnnouncement.setCreateTime(new Date());
        sysAnnouncement.setSendTime(new Date());
        sysAnnouncement.setSendStatus("1");
        sysAnnouncement.setMsgType("ALL");
        sysAnnouncement.setMsgContent("1");
        sysAnnouncement.setPriority("H");
        sysAnnouncementService.save(sysAnnouncement);

        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param ysyWithdrawLog
     * @return
     */
    @AutoLog(value = "提现记录表-编辑")
    @ApiOperation(value = "提现记录表-编辑", notes = "提现记录表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody YsyWithdrawLog ysyWithdrawLog) {

        YsyWithdrawLog ysyWithdrawLogDB = ysyWithdrawLogService.getOne(Wrappers.<YsyWithdrawLog>lambdaQuery()
                .eq(YsyWithdrawLog::getId, ysyWithdrawLog.getId()));

        if (ysyWithdrawLogDB.getStatus() != 0) {
            return Result.error("该订单已审核，请勿重复审核");
        }

        if (ysyWithdrawLog.getStatus() == 2) {
            //审核未通过，提现金额返回原账户
            YsyUsers ysyUsers = ysyUsersMapper.selectOne(Wrappers.<YsyUsers>lambdaQuery()
                    .eq(YsyUsers::getId, ysyWithdrawLog.getUserId()));
            ysyUsers.setBalance(ysyUsers.getBalance().add(ysyWithdrawLog.getMoney()));
            ysyUsersMapper.updateById(ysyUsers);
        }

        ysyWithdrawLogService.updateById(ysyWithdrawLog);
        return Result.ok("编辑成功!");
    }

    /**
     * 同步用户未结算资金到可用余额
     *
     * @param
     * @return
     */
//    @AutoLog(value = "提现记录表-同步用户未结算资金到可用余额")
    @ApiOperation(value = "提现记录表-同步用户未结算资金到可用余额", notes = "提现记录表-同步用户未结算资金到可用余额")
    @GetMapping(value = "/toUserFreeToUseMoney")
    public Result<?> toUserFreeToUseMoney() {
        return ysyWithdrawLogService.toUserFreeToUseMoney();
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "提现记录表-通过id删除")
    @ApiOperation(value = "提现记录表-通过id删除", notes = "提现记录表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        ysyWithdrawLogService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "提现记录表-批量删除")
    @ApiOperation(value = "提现记录表-批量删除", notes = "提现记录表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.ysyWithdrawLogService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "提现记录表-通过id查询")
    @ApiOperation(value = "提现记录表-通过id查询", notes = "提现记录表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        YsyWithdrawLog ysyWithdrawLog = ysyWithdrawLogService.getById(id);
        return Result.ok(ysyWithdrawLog);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param ysyWithdrawLog
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YsyWithdrawLog ysyWithdrawLog) {
        return super.exportXls(request, ysyWithdrawLog, YsyWithdrawLog.class, "提现记录表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, YsyWithdrawLog.class);
    }

}
